package main

import (
	"flag"
	"fmt"
	"log"
	"net/http"
	"path/filepath"
	"runtime"

	"ai-collections/pkg/config"
	"ai-collections/pkg/handlers"
	"ai-collections/pkg/logger"
	"ai-collections/pkg/models"
	"ai-collections/pkg/services"

	"github.com/gin-gonic/gin"
)

func main() {
	// 添加命令行参数
	configPathFlag := flag.String("config", "", "配置文件路径")
	flag.Parse()

	// 获取项目根目录（仅用于开发环境）
	_, filename, _, _ := runtime.Caller(0)
	rootDir := filepath.Join(filepath.Dir(filename), "../..")

	// 加载配置
	var configPath string
	if *configPathFlag != "" {
		configPath = *configPathFlag
	} else {
		configPath = filepath.Join(rootDir, "pkg/config/config.json")
	}

	// 加载配置
	cfg, err := config.LoadConfig(configPath)
	if err != nil {
		log.Fatalf("Error loading config: %v", err)
	}

	// 初始化日志系统
	if err := logger.Init(
		cfg.Logging.Level,
		cfg.Logging.ConsoleLevel,
		cfg.Logging.FileLevel,
		cfg.Logging.FilePath,
	); err != nil {
		log.Fatalf("Failed to initialize logger: %v", err)
	}
	defer logger.Close()

	logger.Info("Loading config from: %s", configPath)
	logger.Info("Log level set to: %s (console: %s, file: %s)",
		cfg.Logging.Level, cfg.Logging.ConsoleLevel, cfg.Logging.FileLevel)

	// 设置 Gin 模式
	if cfg.Server.GinMode != "" {
		gin.SetMode(cfg.Server.GinMode)
		logger.Info("Gin mode set to: %s", cfg.Server.GinMode)
	}

	// 设置加密密钥
	handlers.SetEncryptionKey([]byte(cfg.Security.EncryptionKey))

	// 初始化API服务URLs
	services.InitAPIURLs(cfg.API.ClaudeBaseURL, cfg.API.PlusBaseURL, cfg.API.FingerprintBaseURL)
	logger.Info("Initialized API services with Claude URL: %s, Plus URL: %s, Fingerprint URL: %s",
		cfg.API.ClaudeBaseURL, cfg.API.PlusBaseURL, cfg.API.FingerprintBaseURL)

	// 初始化Redis Token服务
	if err := services.InitRedisTokenService(&cfg.Redis); err != nil {
		logger.Fatal("Failed to initialize Redis token service: %v", err)
	}
	logger.Info("Redis token service initialized with host: %s, port: %s",
		cfg.Redis.Host, cfg.Redis.Port)

	// 初始化公告服务
	dataDir := cfg.Server.DataDir
	if dataDir == "" {
		logger.Fatal("公告保存路径未设置,请在配置文件中指定")
	}

	logger.Info("Using data directory: %s", dataDir)
	noticeService, err := models.NewNoticeService(dataDir)
	if err != nil {
		logger.Fatal("Failed to initialize notice service: %v", err)
	}
	handlers.SetNoticeService(noticeService)

	// 初始化系统配置服务
	configService, err := models.NewConfigService(dataDir)
	if err != nil {
		logger.Fatal("Failed to initialize config service: %v", err)
	}
	handlers.SetConfigService(configService)
	logger.Info("System configuration service initialized")

	// 创建Gin引擎
	r := gin.Default()

	// 创建根路由组
	root := r.Group("/ai-collections")
	{
		// 静态文件服务配置
		staticDir := cfg.Server.StaticDir
		if staticDir == "" {
			logger.Fatal("页面模板路径未配置，请在配置文件中指定")
		}
		logger.Info("Using static directory: %s", staticDir)
		root.Static("/static", staticDir)

		// 设置处理程序的静态目录
		handlers.SetStaticDir(staticDir)

		// 路由配置
		root.GET("/", handlers.CollectionsHandler)
		root.POST("/validate-token", handlers.ValidateTokenHandler)
		root.POST("/create-token", handlers.CreateTokenHandler)

		// 添加清除Cookie的接口
		root.POST("/clear-claude-cookie", handlers.ClearClaudeSessionCookieHandler)

		// 公告相关路由
		root.GET("/notice", handlers.NoticeListHandler)
		root.GET("/notice/:id", handlers.NoticeDetailHandler)
		root.GET("/notice/edit/:id", handlers.NoticeEditHandler)
		root.GET("/notice/new", handlers.NoticeNewHandler)
		root.POST("/notice/save", handlers.NoticeSaveHandler)
		root.POST("/notice/delete/:id", handlers.NoticeDeleteHandler)

		// 系统配置API
		root.GET("/api/config", handlers.GetConfigHandler)
		root.POST("/api/config", handlers.UpdateConfigHandler)

		// 健康检查路由
		root.GET("/health", func(c *gin.Context) {
			c.String(http.StatusOK, "Service is healthy!")
		})
	}

	// 启动服务器
	port := cfg.Server.Port
	if port == "" {
		port = "8080"
	}
	serverAddr := fmt.Sprintf("%s:%s", cfg.Server.Host, port)
	logger.Info("Server is starting on %s...", serverAddr)
	if err := r.Run(serverAddr); err != nil {
		logger.Fatal("Server failed to start: %v", err)
	}
}
